import http from "http";
import methods from "methods";
import url from "url";

// 面向对象  函数式编程

// express 就是基于es5来实现（没有promise）所有的写法都是通过回调来处理的
function createApplication() {
  const routes = [];
  function done(req, res) {
    // 如果路由系统中的层不存在则调用此方法来结束响应
    res.end(`Cannot ${req.method} ${req.url}`);
  }
  let app = {
    listen(...args) {
      const server = http.createServer((req, res) => {
        const { pathname, query } = url.parse(req.url, true);
        const method = req.method.toLowerCase();
        for (let i = 0; i < routes.length; i++) {
          let {
            path: layerPath,
            method: layerMethod,
            handler: layerHandler,
          } = routes[i];

          if (pathname === layerPath && method === layerMethod) {
            return layerHandler(req, res);
          }
        }
        done(req, res);
      });
      server.listen(...args);
    },
  };
  methods.forEach((method) => {
    app[method] = (path, handler) => {
      let layer = {
        path,
        method,
        handler,
      };
      routes.push(layer);
    };
  });
  return app;
}

export default createApplication;
